package com.yimin.portalwebsite.httpserver.handlers;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    // HTML模板目录
    private static final String WEB_ROOT = "webroot";

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
        // 只支持GET方法
        if (!request.method().equals(HttpMethod.GET)) {
            sendError(ctx, METHOD_NOT_ALLOWED);
            return;
        }

        try {
            // 获取请求路径
            String uri = request.uri();
            if (uri.equals("/")) {
                uri = "/index.html";
            }

            // 安全处理路径
            uri = URLDecoder.decode(uri, "UTF-8");
            if (uri.contains("..")) {
                sendError(ctx, FORBIDDEN);
                return;
            }

            // 构建文件路径
            String filePath = WEB_ROOT + uri;
            Path path = Paths.get(filePath);

            if (!Files.exists(path)) {
                sendError(ctx, NOT_FOUND);
                return;
            }

            // 读取文件内容
            byte[] fileContent = Files.readAllBytes(path);
            String contentType = getContentType(filePath);

            // 发送HTTP响应
            sendResponse(ctx, fileContent, contentType);

        } catch (Exception e) {
            sendError(ctx, INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        }
    }

    private String getContentType(String filePath) {
        if (filePath.endsWith(".html")) {
            return "text/html; charset=UTF-8";
        } else if (filePath.endsWith(".css")) {
            return "text/css";
        } else if (filePath.endsWith(".js")) {
            return "application/javascript";
        } else if (filePath.endsWith(".png")) {
            return "image/png";
        } else if (filePath.endsWith(".jpg") || filePath.endsWith(".jpeg")) {
            return "image/jpeg";
        } else {
            return "text/plain";
        }
    }

    private void sendResponse(ChannelHandlerContext ctx, byte[] content, String contentType) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HTTP_1_1, OK, Unpooled.wrappedBuffer(content));

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType);
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

        ctx.writeAndFlush(response);
    }

    private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HTTP_1_1, status,
                Unpooled.copiedBuffer("Error: " + status + "\r\n", CharsetUtil.UTF_8));

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }


    // 在HttpRequestHandler中添加模板解析方法
    private String parseTemplate(String htmlContent) {
        // 简单的插槽语法解析 - 替换 ${variable} 格式
        String result = htmlContent;

        // 模拟数据 - 实际中可以从前端请求或数据库获取
        result = result.replace("${userName}", "Netty用户");
        result = result.replace("${currentTime}", java.time.LocalDateTime.now().toString());
        result = result.replace("${serverStatus}", "运行正常");

        // 你可以在这里添加更复杂的模板解析逻辑
        // 比如条件判断、循环等

        return result;
    }

    // 修改文件读取部分，在发送响应前解析模板
    private void sendHtmlResponse(ChannelHandlerContext ctx, String htmlContent) {
        // 解析模板插槽
        String parsedContent = parseTemplate(htmlContent);

        FullHttpResponse response = new DefaultFullHttpResponse(
                HTTP_1_1, OK, Unpooled.copiedBuffer(parsedContent, CharsetUtil.UTF_8));

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

        ctx.writeAndFlush(response);
    }


}